package 可视化算法.概率模拟算法.三门问题;

/**
 * @author MT
 * 蒙特卡洛算法解决三门问题
 *
 * @date 2019-11-29 14:28
 */
public class ThreeGatesExperiment {
    private int N;

    public ThreeGatesExperiment(int N) {
        if (N <= 0) {
            throw new IllegalArgumentException("N 不能小于零");
        }
        this.N = N;
    }

    public void run(boolean changeDoor) {

        int winNum = 0;
        for (int i = 0; i < N; i++) {
            if (play(changeDoor)) {
                winNum++;
            }
        }

        System.out.println(changeDoor ? "Change" : "Not Change");

        System.out.println("三门问题胜利概率为：" + (double) winNum / N);
    }

    private boolean play(boolean changeDoor) {
        // Door 0,1,2
        // 设置中奖门
        int prizeDoor = (int) (Math.random() * 3);
        // 设置玩家选中的门
        int playerChoice = (int) (Math.random() * 3);

        if (playerChoice == prizeDoor) {
            // 如果奖品是玩家选中的门，那么换门则失败，不换则成功
            return changeDoor ? false : true;
        } else {
            // 如果奖品不是玩家选中的门，那么不换门成功，换门失败
            return changeDoor ? true : false;
        }
    }

    public static void main(String[] args) {
        int N = 100000;

        ThreeGatesExperiment exp = new ThreeGatesExperiment(N);
        exp.run(true);
        exp.run(false);
    }
}
